﻿#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=Resources\Main.ico
#AutoIt3Wrapper_Outfile=Imgx.exe
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Res_Comment=USBest Imgx created by Tung.
#AutoIt3Wrapper_Res_Description=Backup and resize FieldComm Images - Server only.
#AutoIt3Wrapper_Res_Fileversion=1.0.0.17
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=y
#AutoIt3Wrapper_Res_LegalCopyright=USBest Imgx created by Tung.
#AutoIt3Wrapper_Res_Language=1033
#AutoIt3Wrapper_Res_Icon_Add=Resources\214.ico
#AutoIt3Wrapper_Res_Icon_Add=Resources\111.ico
#AutoIt3Wrapper_Res_Icon_Add=Resources\206.ico
#AutoIt3Wrapper_Res_Icon_Add=Resources\211.ico
#AutoIt3Wrapper_Res_Icon_Add=Resources\209.ico
#AutoIt3Wrapper_Res_Icon_Add=Resources\205.ico
#AutoIt3Wrapper_Res_File_Add=Resources\wintop.jpg, rt_rcdata, wintop
#AutoIt3Wrapper_Res_File_Add=Resources\windown.jpg, rt_rcdata, windown
#AutoIt3Wrapper_Res_File_Add=Resources\214.ico, rt_rcdata, backupicon
#AutoIt3Wrapper_Res_File_Add=Resources\205.ico, rt_rcdata, resizeicon
#AutoIt3Wrapper_Res_File_Add=Resources\206.ico, rt_rcdata, copyicon
#AutoIt3Wrapper_Res_File_Add=Resources\Workorder.jpg, rt_rcdata, WOPic
#AutoIt3Wrapper_Res_File_Add=Resources\Width.jpg, rt_rcdata, WOWidth
#AutoIt3Wrapper_Res_File_Add=Resources\Height.jpg, rt_rcdata, WOHeight
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#include <ComboConstants.au3>
#include <ButtonConstants.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <GUIListBox.au3>
#include <ProgressConstants.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <File.au3>
#include <Date.au3>
#include <Array.au3>
#include <GDIPlus.au3>
#include <UpdownConstants.au3>
#include <UDFs\_LargeFileCopy.au3>
#include <UDFs\Resources.au3>
#include <UDFs\_Setting.au3>
#include <UDFs\_FileListToArrayEx.au3>
#include <UDFs\_ImageResize.au3>
#include <Misc.au3>

_Singleton("Imgx")
Opt("GUIOnEventMode", 1)

Global const $username = EnvGet("USERNAME")
Global $MainForm, $VarOrder, $VarWidth, $VarHeight, $VarStatus, $VALabel, $Progressbar, $cLogFile, $StatusLabel

;Define config variable.
Global $TrReg = 1
Global $sPath_ini = @AppDataCommonDir & '\Tstudio\Config.ini'
Global $sPath_reg = 'HKEY_CURRENT_USER\Software\TStudio'
Global $setting[2]

; #ACTION# ;=================================================================================
; Description ........: Check Tstudio Folder.
; ===========================================================================================
If DirGetSize(@AppDataCommonDir & "\TStudio\") = -1 Then
    DirCreate(@AppDataCommonDir & "\TStudio\")
EndIf

; #ACTION# ;=================================================================================
; Description ........: Check a value from ini-file or registry.
; ===========================================================================================
If _RegExists($sPath_reg) Then
	$TrReg = 1
	_ReadSet($sPath_reg, $TrReg)
Else
	If FileExists($sPath_ini) Then
		$TrReg = 0
		_ReadSet($sPath_ini, $TrReg)
	Else
		$TrReg = 1
		_DefWriteSet($sPath_reg, $TrReg)
		_DefWriteSet($sPath_ini, 0)
	EndIf
EndIf

#Region ### START GUI section ###
$MainForm = GUICreate("Backup & Resize Tool", 321, 370, 760, 414)

GUISetOnEvent($GUI_EVENT_CLOSE, "On_Exit")
GUISetBkColor(0xFFFFFF)

Local $wintop = GUICtrlCreatePic("", -275, -26, 701, 92)
GUICtrlSetState($wintop, $GUI_DISABLE)

If Not @compiled Then
	GUICtrlSetImage($wintop, @ScriptDir & "\Resources\wintop.jpg")
Else
	_ResourceSetImageToCtrl($wintop, "wintop") ; set JPG image to picture control from resource
EndIf

Local $windown = GUICtrlCreatePic("", -50, 313, 640, 57)
GUICtrlSetState($windown, $GUI_DISABLE)

If Not @compiled Then
	GUICtrlSetImage($windown, @ScriptDir & "\Resources\windown.jpg")
Else
	_ResourceSetImageToCtrl($windown, "windown") ; set JPG image to picture control from resource
EndIf

Local $LogoTop = GUICtrlCreateLabel("USBEST imgx", 13, 7, 200, 50)
GUICtrlSetFont($LogoTop, 14, 700, 2, "Segoe UI")
GUICtrlSetColor($LogoTop, 0x3399FF)
GUICtrlSetBkColor($LogoTop, $GUI_BKCOLOR_TRANSPARENT)

Local $WOPic = GUICtrlCreatePic("", 10, 45, 180, 23)
GUICtrlSetState($WOPic, $GUI_DISABLE)

If Not @compiled Then
	GUICtrlSetImage($WOPic, @ScriptDir & "\Resources\Workorder.jpg")
Else
	_ResourceSetImageToCtrl($WOPic, "WOPic") ; set JPG image to picture control from resource
EndIf

$VarOrder = GUICtrlCreateInput("", 115, 50, 70, 12, BitOR($ES_CENTER,$ES_NUMBER), 0)
GUICtrlSetState($VarOrder, $GUI_ONTOP)
GUICtrlSendMsg($VarOrder, $EM_SETCUEBANNER, False, "Input Order")
GUICtrlSetLimit($VarOrder, 10)
GUICtrlSetTip($VarOrder, "Unique Order Number.")

;###### STATUS ########
$StatusLabel = GUICtrlCreateLabel("", 195, 48, 110, 17, BitOR($SS_CENTER,$SS_CENTERIMAGE))
GUICtrlSetColor($StatusLabel, 0x000000)
GUICtrlSetBkColor($StatusLabel, 0xFFFFFF)

Local $Group1 = GUICtrlCreateGroup("Main", 10, 70, 300, 80)

Local $BtnBackup = GUICtrlCreateButton(" Backup", 17, 88, 70, 25)
GUICtrlSetOnEvent($BtnBackup, "Backup_Images")
If Not @compiled Then
	GUICtrlSetImage($BtnBackup, @ScriptDir & "\Resources\214.ico")
Else
	GUICtrlSetImage($BtnBackup, @ScriptFullPath, -5, 0) ; set JPG image to picture control from resource
EndIf

Local $BtnRestore = GUICtrlCreateButton(" Restore", 90, 88, 70, 25)
GUICtrlSetOnEvent($BtnRestore, "Restore_Images")
If Not @compiled Then
	GUICtrlSetImage($BtnRestore, @ScriptDir & "\Resources\111.ico")
Else
	GUICtrlSetImage($BtnRestore, @ScriptFullPath, -6, 0) ; set JPG image to picture control from resource
EndIf

Local $BtnCopy = GUICtrlCreateButton(" Copy", 161, 88, 70, 25)
GUICtrlSetOnEvent($BtnCopy, "Copy_Images")
If Not @compiled Then
	GUICtrlSetImage($BtnCopy, @ScriptDir & "\Resources\206.ico")
Else
	GUICtrlSetImage($BtnCopy, @ScriptFullPath, -7, 0) ; set JPG image to picture control from resource
EndIf

Local $BtnMove = GUICtrlCreateButton(" Move", 232, 88, 70, 25)
GUICtrlSetOnEvent($BtnMove, "Move_Images")
If Not @compiled Then
	GUICtrlSetImage($BtnMove, @ScriptDir & "\Resources\211.ico")
Else
	GUICtrlSetImage($BtnMove, @ScriptFullPath, -8, 0) ; set JPG image to picture control from resource
EndIf

Local $DuplicateMethod = GUICtrlCreateCombo("MD5 Files Integrity", 18, 118, 140, 100, BitOR($CBS_DROPDOWN,$CBS_AUTOHSCROLL))
GUICtrlSetData($DuplicateMethod, "MD5 Files Integrity|CRC Compare|File Names")
GUICtrlSetState($DuplicateMethod, $GUI_DISABLE)
Local $BtnDuplicate = GUICtrlCreateButton(" Duplicate Check", 160, 116, 142, 25)
;~ GUICtrlSetOnEvent($BtnDuplicate, "Move_Images")
If Not @compiled Then
	GUICtrlSetImage($BtnDuplicate, @ScriptDir & "\Resources\209.ico")
Else
	GUICtrlSetImage($BtnDuplicate, @ScriptFullPath, -9, 0) ; set JPG image to picture control from resource
EndIf
GUICtrlSetState($BtnDuplicate, $GUI_DISABLE)

Local $LblStatus = GUICtrlCreateLabel("Status:", 11, 157, 37, 17)
$VarStatus = GUICtrlCreateLabel("", 50, 157, 250, 17)
$Progressbar = GUICtrlCreateProgress(10, 175, 300, 10, $PBS_SMOOTH)

Local $Group2 = GUICtrlCreateGroup("", 10, 190, 300, 50)
;~ Local $LblWidth = GUICtrlCreateLabel("Width:", 20, 210, 35, 17)
Local $WOPic = GUICtrlCreatePic("", 15, 206, 100, 23)
GUICtrlSetState($WOPic, $GUI_DISABLE)

If Not @compiled Then
	GUICtrlSetImage($WOPic, @ScriptDir & "\Resources\Width.jpg")
Else
	_ResourceSetImageToCtrl($WOPic, "WOWidth") ; set JPG image to picture control from resource
EndIf
$VarWidth = GUICtrlCreateInput($setting[0], 80, 211, 30, 14, BitOR($ES_CENTER,$ES_NUMBER), 0)
GUICtrlSetLimit($VarWidth, 4)
Local $ip1 = GUICtrlRead($VarWidth)
;~ Local $VarUDWidth = GUICtrlCreateUpdown($VarWidth, BitOR($UDS_ARROWKEYS, $UDS_NOTHOUSANDS, $UDS_WRAP))
;~ GUICtrlSetLimit($VarUDWidth, 1600, 200)


;~ Local $LblHeight = GUICtrlCreateLabel("Height:", 120, 210, 38, 17)
Local $WOPic = GUICtrlCreatePic("", 120, 206, 100, 23)
GUICtrlSetState($WOPic, $GUI_DISABLE)

If Not @compiled Then
	GUICtrlSetImage($WOPic, @ScriptDir & "\Resources\Height.jpg")
Else
	_ResourceSetImageToCtrl($WOPic, "WOHeight") ; set JPG image to picture control from resource
EndIf

$VarHeight = GUICtrlCreateInput($setting[1], 185, 211, 30, 14, BitOR($ES_CENTER,$ES_NUMBER), 0)
GUICtrlSetLimit($VarHeight, 4)
Local $ip2 = GUICtrlRead($VarHeight)
;~ Local $VarUDHeight = GUICtrlCreateUpdown($VarHeight, BitOR($UDS_ARROWKEYS, $UDS_NOTHOUSANDS, $UDS_WRAP))
;~ GUICtrlSetLimit($VarUDHeight, 1600, 200)

Local $BtnResize = GUICtrlCreateButton(" Resize", 226, 205, 75, 25)
GUICtrlSetOnEvent($BtnResize, "Resize_Images")
If Not @compiled Then
	GUICtrlSetImage($BtnResize, @ScriptDir & "\Resources\205.ico")
Else
;	_ResourceSetImageToCtrl($BtnResize, "resizeicon") ; set JPG image to picture control from resource
	GUICtrlSetImage($BtnResize, @ScriptFullPath, -10, 0) ; set JPG image to picture control from resource
EndIf

$VALabel = GUICtrlCreateLabel("Click here to verify.", 10, 250, 300, 17, BitOR($SS_CENTER,$SS_CENTERIMAGE))
GUICtrlSetColor($VALabel, 0x000000)
GUICtrlSetBkColor($VALabel, 0xB9D1EA)
GUICtrlSetOnEvent($VALabel, "Verify_Access")

Local $Group3 = GUICtrlCreateGroup("Information", 10, 275, 300, 87)
Local $LblInfo1 = GUICtrlCreateLabel("Max images size 1600 x 1600 pixels.", 19, 295, 270, 17)
GUICtrlSetBkColor($LblInfo1, $GUI_BKCOLOR_TRANSPARENT)
Local $LblInfo2 = GUICtrlCreateLabel("Server access required prior using.", 19, 308, 270, 17)
GUICtrlSetBkColor($LblInfo2, $GUI_BKCOLOR_TRANSPARENT)

Local $LblInfo3 = GUICtrlCreateLabel("Email TechSupport for access or report bugs/glitches.", 19, 340, 258, 17)
GUICtrlSetBkColor($LblInfo3, $GUI_BKCOLOR_TRANSPARENT)


;Hidden Menu to open folder.
Global $Open_Folder = GUICtrlCreateDummy()
GUICtrlSetOnEvent($Open_Folder, "Open_Folder")
Global $MainForm_AccelTable[1][2] = [["^+{F9}", $Open_Folder]]
GUISetAccelerators($MainForm_AccelTable)

GUISetState()
GUIRegisterMsg($WM_COMMAND, "WM_COMMAND");only used for EN_CHANGE so far

#EndRegion ### END Koda GUI section ###

While 1
	Sleep(200)
WEnd

Func Backup_Images()
	GUICtrlSetData($Progressbar, 0)
	; "###Null###" "C:\order\"
	Local $SourcePath = "###Null###" & GUICtrlRead($VarOrder) & "\Photos\"
	Local $DestPath = $SourcePath & "Backup\"
	Local $TotalDirSize = DirGetSize($SourcePath)
	Local $FilesArr = _FileListToArrayEx($SourcePath,"*",9)
	Local $FilesCount = UBound($FilesArr)-1
	Local $Progress=0, $Counter, $TimeRemained, $ReadySize, $Ready
    Local $CurrentFilePath, $CurrentFileName, $CurrentFilePathName, $CurrentParentDirName
	Local $ProgressStep = 100 / $FilesCount
	Local $sizeSourcePath = DirIsEmpty($SourcePath)
	Local $search, $Found, $NotFound, $matchcount = 0, $notmatchcount = 0

	If GUICtrlRead($VarOrder) == "" Then
		GUICtrlSetData($StatusLabel, "What's the order?")
		blink()
	else
		If FileExists($SourcePath) and StringInStr(FileGetAttrib($SourcePath),"D") then
			If $sizeSourcePath = -1 Then ;check if photos directory is empty
					GUICtrlSetData($VarStatus, "Order has no photo. Backup cancelled.")
			Else ;photos directory not empty
				If FileExists($DestPath) and StringInStr(FileGetAttrib($DestPath),"D") then ;check if backup folder exist
				;time to compare both directory
					For $i = 1 To UBound($FilesArr)-1
						$CurrentFilePath = $FilesArr[$i]
						$CurrentFileName = StringRegExpReplace($CurrentFilePath, "^.*\\", "")
						$search = $DestPath & $CurrentFileName

						If FileExists($search) then
							$matchcount += 1
							$Found &= $FilesArr[$i] & @LF
						Else
							$notmatchcount += 1
							$notfound &= $FilesArr[$i] & @LF
							_LargeFileCopy($CurrentFilePath, $DestPath, BitOR(1,2,8))
						EndIf
						;Done
						GUICtrlSetData($VarStatus, $notfound & " is backing up.")
					Next

					If $notmatchcount = "0" Then
						GUICtrlSetData($VarStatus, "No new image since last backup.")
					Else
						GUICtrlSetData($VarStatus, $notmatchcount & " new images had been backup!")
					EndIf
				Else ; backup doesn't exist
					;If DirGetSize($DestPath) = -1 Then
					DirCreate($DestPath)
					;EndIf
					If IsArray($FilesArr) Then
						For $i = 1 To UBound($FilesArr)-1
							$CurrentFilePath = $FilesArr[$i]
							$CurrentFileName = StringRegExpReplace($CurrentFilePath, "^.*\\", "")
							$CurrentFilePathName = StringReplace($CurrentFilePath, $SourcePath & "\", "")
							$CurrentParentDirName = _GetParentDirName($CurrentFilePath)

							$Progress += $ProgressStep
							$Counter += 1
							$ReadySize = FileGetSize($CurrentFilePath)
							$Ready = $Counter & "/" & $FilesCount
							$TimeRemained = _GetTimeRemained($TotalDirSize, $ReadySize, $FilesCount, $Counter)

							GUICtrlSetData($Progressbar, $Progress)
							GUICtrlSetData($VarStatus, $Ready & "  -  " & $CurrentFileName)
							_LargeFileCopy($CurrentFilePath, $DestPath, BitOR(1,2,8))

						Next
						GUICtrlSetData($VarStatus, $FilesCount & " images had been backup!")
					EndIf
				EndIf
			EndIf
		Else
			GUICtrlSetData($StatusLabel, "Not Found!")
		blink()
		EndIf
	EndIf

	_Crypt_Shutdown()
EndFunc

Func Restore_Images()
	GUICtrlSetData($Progressbar, 0)
	; "###Null###" "C:\order\"
	Local $DestPath = "###Null###" & GUICtrlRead($VarOrder) & "\Photos\"
	Local $SourcePath = $DestPath & "Backup\"
	Local $TotalDirSize = DirGetSize($SourcePath)
	Local $FilesArr = _FileListToArrayEx($SourcePath,"*",9)
	Local $FilesCount = UBound($FilesArr)-1
	Local $Progress=0, $Counter, $TimeRemained, $ReadySize, $Ready
    Local $CurrentFilePath, $CurrentFileName, $CurrentFilePathName, $CurrentParentDirName
	Local $ProgressStep = 100 / $FilesCount
	Local $sizeSourcePath = DirIsEmpty($SourcePath)

	If GUICtrlRead($VarOrder) == "" Then
		GUICtrlSetData($StatusLabel, "What's the order?")
		blink()
	else
		If FileExists($SourcePath) and StringInStr(FileGetAttrib($SourcePath),"D") then
			If $sizeSourcePath = -1 Then
					GUICtrlSetData($VarStatus, "No backup was found!")
			Else
				If IsArray($FilesArr) Then
					For $i = 1 To UBound($FilesArr)-1
						$CurrentFilePath = $FilesArr[$i]
						$CurrentFileName = StringRegExpReplace($CurrentFilePath, "^.*\\", "")
						$CurrentFilePathName = StringReplace($CurrentFilePath, $SourcePath & "\", "")
						$CurrentParentDirName = _GetParentDirName($CurrentFilePath)

						$Progress += $ProgressStep
						$Counter += 1
						$ReadySize = FileGetSize($CurrentFilePath)
						$Ready = $Counter & "/" & $FilesCount
						$TimeRemained = _GetTimeRemained($TotalDirSize, $ReadySize, $FilesCount, $Counter)

						GUICtrlSetData($Progressbar, $Progress)
						GUICtrlSetData($VarStatus, $Ready & "  -  " & $CurrentFileName)
						_LargeFileCopy($CurrentFilePath, $DestPath, BitOR(1,2,8))

					Next
					GUICtrlSetData($VarStatus, $FilesCount & " files restored!")
				EndIf
			EndIf
		Else
			GUICtrlSetData($StatusLabel, "Not Found!")
		blink()
		EndIf
	EndIf

	_Crypt_Shutdown()
EndFunc

Func Copy_Images()
	GUICtrlSetData($Progressbar, 0)
	; "###Null###" "C:\order\"
	Local $SourcePath = "###Null###" & GUICtrlRead($VarOrder) & "\Photos\"
	Local $DestPath
	Local $TotalDirSize = DirGetSize($SourcePath)
	Local $FilesArr = _FileListToArrayEx($SourcePath,"*",9)
	Local $FilesCount = UBound($FilesArr)-1
	Local $Progress=0, $Counter, $TimeRemained, $ReadySize, $Ready
    Local $CurrentFilePath, $CurrentFileName, $CurrentFilePathName, $CurrentParentDirName
	Local $ProgressStep = 100 / $FilesCount
	Local $sizeSourcePath = DirIsEmpty($SourcePath)
	Local $search, $Found, $NotFound, $matchcount = 0, $notmatchcount = 0

	If GUICtrlRead($VarOrder) == "" Then
		GUICtrlSetData($StatusLabel, "What's the order?")
		blink()
	Else
		If FileExists($SourcePath) and StringInStr(FileGetAttrib($SourcePath),"D") then
			If $sizeSourcePath = -1 Then ;check if photos directory is empty
					GUICtrlSetData($VarStatus, "Order has no photo. Copy cancelled.")
			Else
				$DestPath = FileSelectFolder("Choose where you want to copy.","",5,@ScriptDir)
				If @error = 1 Then

				Else
					If IsArray($FilesArr) Then
						For $i = 1 To UBound($FilesArr)-1
							$CurrentFilePath = $FilesArr[$i]
							$CurrentFileName = StringRegExpReplace($CurrentFilePath, "^.*\\", "")
							$CurrentFilePathName = StringReplace($CurrentFilePath, $SourcePath & "\", "")
							$CurrentParentDirName = _GetParentDirName($CurrentFilePath)

							$Progress += $ProgressStep
							$Counter += 1
							$ReadySize = FileGetSize($CurrentFilePath)
							$Ready = $Counter & "/" & $FilesCount
							$TimeRemained = _GetTimeRemained($TotalDirSize, $ReadySize, $FilesCount, $Counter)

							GUICtrlSetData($Progressbar, $Progress)
							GUICtrlSetData($VarStatus, $Ready & "  -  " & $CurrentFileName)
							_LargeFileCopy($CurrentFilePath, $DestPath, BitOR(1,2,8))

						Next
						GUICtrlSetData($VarStatus, $FilesCount & " images had been copied.")
					EndIf
				Endif
			EndIf
		Else
			GUICtrlSetData($StatusLabel, "Not Found!")
		blink()
		EndIf
	EndIf

	_Crypt_Shutdown()
EndFunc

Func Move_Images()
	GUICtrlSetData($Progressbar, 0)
	; "###Null###" "C:\order\"
	Local $SourcePath = "###Null###" & GUICtrlRead($VarOrder) & "\Photos\"
	Local $DestPath = $SourcePath & "Backup\"
	Local $TotalDirSize = DirGetSize($SourcePath)
	Local $FilesArr = _FileListToArrayEx($SourcePath,"*",9)
	Local $FilesCount = UBound($FilesArr)-1
	Local $Progress=0, $Counter, $TimeRemained, $ReadySize, $Ready
    Local $CurrentFilePath, $CurrentFileName, $CurrentFilePathName, $CurrentParentDirName
	Local $ProgressStep = 100 / $FilesCount
	Local $sizeSourcePath = DirIsEmpty($SourcePath)
	Local $search, $Found, $NotFound, $matchcount = 0, $notmatchcount = 0

	If GUICtrlRead($VarOrder) == "" Then
		GUICtrlSetData($StatusLabel, "What's the order?")
		blink()
	else
		If FileExists($SourcePath) and StringInStr(FileGetAttrib($SourcePath),"D") then
			If $sizeSourcePath = -1 Then ;check if photos directory is empty
					GUICtrlSetData($VarStatus, "Order has no photo. Move cancelled.")
			Else ;photos directory not empty
				If FileExists($DestPath) and StringInStr(FileGetAttrib($DestPath),"D") then ;check if backup folder exist
				;time to compare both directory
					For $i = 1 To UBound($FilesArr)-1
						$CurrentFilePath = $FilesArr[$i]
						$CurrentFileName = StringRegExpReplace($CurrentFilePath, "^.*\\", "")
						$search = $DestPath & $CurrentFileName

						If FileExists($search) then
							$matchcount += 1
							$Found &= $FilesArr[$i] & @LF
						Else
							$notmatchcount += 1
							$notfound &= $FilesArr[$i] & @LF
							_LargeFileCopy($CurrentFilePath, $DestPath, BitOR(1,2,8))
						EndIf
						;Done
						GUICtrlSetData($VarStatus, $notfound & " is moving to backup.")
					Next

					If $notmatchcount = "0" Then
						GUICtrlSetData($VarStatus, "No new image since last moved.")
					Else
						GUICtrlSetData($VarStatus, $notmatchcount & " new images had been moved!")
					EndIf
					FileDelete($SourcePath)
				Else ; backup doesn't exist
					;If DirGetSize($DestPath) = -1 Then
					DirCreate($DestPath)
					;EndIf
					If IsArray($FilesArr) Then
						For $i = 1 To UBound($FilesArr)-1
							$CurrentFilePath = $FilesArr[$i]
							$CurrentFileName = StringRegExpReplace($CurrentFilePath, "^.*\\", "")
							$CurrentFilePathName = StringReplace($CurrentFilePath, $SourcePath & "\", "")
							$CurrentParentDirName = _GetParentDirName($CurrentFilePath)

							$Progress += $ProgressStep
							$Counter += 1
							$ReadySize = FileGetSize($CurrentFilePath)
							$Ready = $Counter & "/" & $FilesCount
							$TimeRemained = _GetTimeRemained($TotalDirSize, $ReadySize, $FilesCount, $Counter)

							GUICtrlSetData($Progressbar, $Progress)
							GUICtrlSetData($VarStatus, $Ready & "  -  " & $CurrentFileName)
							_LargeFileCopy($CurrentFilePath, $DestPath, BitOR(1,2,8))

						Next
						FileDelete($SourcePath)
						GUICtrlSetData($VarStatus, $FilesCount & " images had been moved!")
					EndIf
				EndIf
			EndIf
		Else
			GUICtrlSetData($StatusLabel, "Not Found!")
		blink()
		EndIf
	EndIf

	_Crypt_Shutdown()
EndFunc

Func Resize_Images()
	GUICtrlSetData($Progressbar, 0)
	Local $SourcePath = "###Null###" & GUICtrlRead($VarOrder) & "\Photos\"
	Local $DestPath = $SourcePath & "Backup\"
	Local $FilesArr = _FileListToArrayEx($SourcePath,"*",9)
	Local $FilesCount = UBound($FilesArr)-1
	Local $ProgressStep = 100 / $FilesCount
	Local $TotalDirSize = DirGetSize($SourcePath)
	Local $tempfolder = $SourcePath & "Temp\" ;Where images will resize and place
	Local $TempCopy, $TempPath, $TempFiles
	Local $Progress=0, $Counter, $TimeRemained, $ReadySize, $Ready
    Local $CurrentFilePath, $CurrentFileName, $CurrentFilePathName, $CurrentParentDirName

	If GUICtrlRead($VarOrder) == "" or GUICtrlRead($VarWidth) == "" or GUICtrlRead($VarHeight) == "" Then
		GUICtrlSetData($StatusLabel, "Missing Something...")
		blink()
	Else
		If FileExists($SourcePath) and StringInStr(FileGetAttrib($SourcePath),"D") then
			If DirGetSize($DestPath) = -1 Then
				Backup_Images()

				If DirGetSize($tempfolder) = -1 Then
					DirCreate($tempfolder)
				EndIf

				If IsArray($FilesArr) Then
					For $i = 1 To UBound($FilesArr) - 1
						$CurrentFilePath = $FilesArr[$i]
						$CurrentFileName = StringRegExpReplace($CurrentFilePath, "^.*\\", "")
						$CurrentFilePathName = StringReplace($CurrentFilePath, $SourcePath & "\", "")
						$CurrentParentDirName = _GetParentDirName($CurrentFilePath)

						$Progress += $ProgressStep
						$Counter += 1
						$ReadySize = FileGetSize($CurrentFilePath)
						$Ready = $Counter & "/" & $FilesCount
						$TimeRemained = _GetTimeRemained($TotalDirSize, $ReadySize, $FilesCount, $Counter)

						GUICtrlSetData($Progressbar, $Progress)
						GUICtrlSetData($VarStatus, $Ready & "  -  " & $CurrentFileName)
						_ImageResize($CurrentFilePath, $tempfolder & $CurrentFileName, GUICtrlRead($VarWidth), GUICtrlRead($VarHeight), True, True, False)
					Next

				EndIf
				;FileDelete($SourcePath)
				$TempCopy = _FileListToArrayEx($tempfolder,"*",9)

				For $i = 1 To UBound($TempCopy)-1
					$TempPath = $TempCopy[$i]
					$TempFiles = StringRegExpReplace($TempPath, "^.*\\", "")
					_LargeFileCopy($TempPath, $SourcePath, BitOR(1,2,8))
					GUICtrlSetData($VarStatus, "Copying: " & $TempFiles)
				Next
				DirRemove($tempfolder, 1)
				GUICtrlSetData($VarStatus, $FilesCount & " files resized.")
				;ShellExecute($SourcePath)
			Else
				Backup_Images()

				If DirGetSize($tempfolder) = -1 Then
					DirCreate($tempfolder)
				EndIf

				If IsArray($FilesArr) Then
					For $i = 1 To UBound($FilesArr) - 1
						$CurrentFilePath = $FilesArr[$i]
						$CurrentFileName = StringRegExpReplace($CurrentFilePath, "^.*\\", "")
						$CurrentFilePathName = StringReplace($CurrentFilePath, $SourcePath & "\", "")
						$CurrentParentDirName = _GetParentDirName($CurrentFilePath)

						$Progress += $ProgressStep
						$Counter += 1
						$ReadySize = FileGetSize($CurrentFilePath)
						$Ready = $Counter & "/" & $FilesCount
						$TimeRemained = _GetTimeRemained($TotalDirSize, $ReadySize, $FilesCount, $Counter)

						GUICtrlSetData($Progressbar, $Progress)
						GUICtrlSetData($VarStatus, $Ready & "  -  " & $CurrentFileName)
						_ImageResize($CurrentFilePath, $tempfolder & $CurrentFileName, GUICtrlRead($VarWidth), GUICtrlRead($VarHeight), True, True, False)
					Next

				EndIf
				;FileDelete($SourcePath)
				$TempCopy = _FileListToArrayEx($tempfolder,"*",9)

				For $i = 1 To UBound($TempCopy)-1
					$TempPath = $TempCopy[$i]
					$TempFiles = StringRegExpReplace($TempPath, "^.*\\", "")
					_LargeFileCopy($TempPath, $SourcePath, BitOR(1,2,8))
					GUICtrlSetData($VarStatus, "Copying: " & $TempFiles)
				Next
				DirRemove($tempfolder, 1)
				GUICtrlSetData($VarStatus, $FilesCount & " files resized.")
				;ShellExecute($SourcePath)
			EndIf
		Else
			GUICtrlSetData($StatusLabel, "Not Found!")
		blink()
		EndIf
	Endif

	_Crypt_Shutdown()
EndFunc

Func Blink()
		GUICtrlSetColor($StatusLabel, 0xFFFFFF)
		GUICtrlSetBkColor($StatusLabel, 0xFF0000)
		sleep(100)
		GUICtrlSetColor($StatusLabel, 0xFFFFFF)
		GUICtrlSetBkColor($StatusLabel, 0xFFFFFF)
		sleep(100)
		GUICtrlSetColor($StatusLabel, 0xFFFFFF)
		GUICtrlSetBkColor($StatusLabel, 0xFF0000)
		sleep(100)
		GUICtrlSetColor($StatusLabel, 0xFFFFFF)
		GUICtrlSetBkColor($StatusLabel, 0xFFFFFF)
		sleep(100)
		GUICtrlSetColor($StatusLabel, 0xFFFFFF)
		GUICtrlSetBkColor($StatusLabel, 0xFF0000)
EndFunc

; #FUNCTION# ;=================================================================================
; Description ........: Reads a value from ini-file or registry.
; Parameters:
;		$sPath - Path or Key
;		$sSection - Section or KeyName
;		$sValueName - Key or ValueName
;		$sDefault - by default
;		$iReg - (0,1)
;                  |0 - ini-file
;                  |1 - registry
; Return values ....: Success - String
; ============================================================================================
Func _ReadSet($sPath, $TrReg)
	$setting[0] = _Setting_Read($sPath, 'Images', 'width', '640', $TrReg)
	$setting[1] = _Setting_Read($sPath, 'Images', 'height', '480', $TrReg)
EndFunc

; #INTERNAL_USE_ONLY#=========================================================================
; Name...........: Write ini or registry setting from programdata/Tstudio/config.ini
; Description ...:
; ============================================================================================
Func _DefWriteSet($sPath, $TrReg)
	$setting[0] = '640'
	$setting[1] = '480'
	_Setting_Write($sPath, 'Images', 'Width', $setting[0], $TrReg)
	_Setting_Write($sPath, 'Images', 'Height', $setting[1], $TrReg)
EndFunc

; #INTERNAL_USE_ONLY#=========================================================================
; Name...........: Write ini or registry setting from programdata/Tstudio/config.ini
; Description ...:
; ============================================================================================
Func LogFileAgeInMinutes( $cLogFile )
Local $cFileDate = FileGetTime( $cLogFile , 0 )  ;Get the Last Modified date and time
Return _DateDiff("m", $cFileDate[0] & "/" & $cFileDate[1] & "/" & $cFileDate[2] & " " & $cFileDate[3] & ":" & $cFileDate[4] & ":" & $cFileDate[5] , _NowCalc())
EndFunc

Func Open_Folder()
	Local $SourcePath = "###Null###" & GUICtrlRead($VarOrder) & "\Photos\"

	If FileExists($SourcePath) and StringInStr(FileGetAttrib($SourcePath),"D") then
	ShellExecute($SourcePath)
	Else
		msgbox(0,"Warning","Please check the order number!  This order was not found on the server.",2)
	EndIf
EndFunc

Func Verify_Access()
	If FileExists("###Null###1000\") Then
		GUICtrlSetData($VALabel, $username & " has access to the server.")
		GUICtrlSetColor($VALabel, 0x000000)
		GUICtrlSetBkColor($VALabel, 0xC0DCC0)
;~ 		GUICtrlSetOnEvent($VALabel, "Verify_Access")
	Else
		GUICtrlSetData($VALabel, $username & " has no access to the server.")
		GUICtrlSetColor($VALabel, 0xFFFFFF)
		GUICtrlSetBkColor($VALabel, 0xFF0000)
;~ 		GUICtrlSetOnEvent($VALabel, "Verify_Access")
	EndIf
EndFunc

Func WM_COMMAND($hWnd, $imsg, $iwParam, $ilParam)
    Local $AtPos, $s1, $s2
    $nNotifyCode = BitShift($iwParam, 16)
	$nID = BitAND($iwParam, 0x0000FFFF)
	$hCtrl = $ilParam

	If $nNotifyCode = $EN_CHANGE Then
		If $ilParam = GUICtrlGetHandle($VarWidth) Then
			$s1 = GUICtrlRead($VarWidth)
			If $s1 = '-' Then $s1 = ''
			If $s1 > 1600 Or $s1 < 1 Then
				GUICtrlSetData($VarWidth, $ip1)
			Else
				$ip1 = $s1
			EndIf
		EndIf
	EndIf

	If $nNotifyCode = $EN_CHANGE Then
		If $ilParam = GUICtrlGetHandle($VarHeight) Then
			$s2 = GUICtrlRead($VarHeight)
			If $s2 = '-' Then $s2 = ''
			If $s2 > 1600 Or $s2 < 1 Then
				GUICtrlSetData($VarHeight, $ip2)
			Else
				$ip2 = $s2
			EndIf
		EndIf
	EndIf
	Return $GUI_RUNDEFMSG

 EndFunc;==>WM_COMMAND

Func _GetParentDirName($FullName)
    Local $LastSlashPos = StringInStr($FullName, "\", 0, -1)
    Local $SecondLastSlashPos = StringInStr($FullName, "\", 0, -2)
    Return StringMid($FullName, $SecondLastSlashPos+1, $LastSlashPos-$SecondLastSlashPos-1)
EndFunc

Func _GetTimeRemained($TotalSize, $CurrentSize, $FilesCount, $CurrentFilesCount)
    Local $NumLevl = 0.5

    If $TotalSize <= $CurrentSize Then Return _SecsToTime(0)

    Switch $FilesCount - $CurrentFilesCount
        Case 0 To 100
            $NumLevl = 0.1
        Case 100 To 1000
            $NumLevl = 0.5
        Case 1000 to 2000
            $NumLevl = 1
        Case Else
            $NumLevl = 2
    EndSwitch

    $Secs = ($TotalSize * $NumLevl) / (3600 * $CurrentFilesCount) - ($CurrentSize * $NumLevl) / (3600 * $CurrentFilesCount)
    Return _SecsToTime($Secs)
EndFunc

Func _SecsToTime($iTicks, $Delim=":")
    If Number($iTicks) >= 0 Then
        $iHours = Int($iTicks / 3600)
        $iTicks = Mod($iTicks, 3600)
        $iMins = Int($iTicks / 60)
        $iSecs = Round(Mod($iTicks, 60))
        If StringLen($iHours) = 1 Then $iHours = "0" & $iHours
        If StringLen($iMins) = 1 Then $iMins = "0" & $iMins
        If StringLen($iSecs) = 1 Then $iSecs = "0" & $iSecs
        Return $iHours & $Delim & $iMins & $Delim & $iSecs
    EndIf
    Return SetError(1, 0, 0)
EndFunc

Func DirIsEmpty($Dir)
    Local $Search, $i, $File

    If StringRight($Dir,1) <> "\" then $Dir = $Dir & "\"

	$Search = FileFindFirstFile($Dir & "*.*")
	If $Search = -1 Then Return -1 ;No files/directories matched the search pattern

    While 1
        $File = FileFindNextFile($Search)
        If @error Then ExitLoop
        $i= $i + 1
        If $i > 2 then ExitLoop
    WEnd
    FileClose($Search)
    If $i = 2 then Return 1 ;Folder Empty
EndFunc


Func On_Exit()
	;Keep the new setting under registry
	_Setting_Write($sPath_reg, 'Images', 'Width', GUICtrlRead($VarWidth), $TrReg)
	_Setting_Write($sPath_reg, 'Images', 'Height', GUICtrlRead($VarHeight), $TrReg)
	_Setting_Write($sPath_ini, 'Images', 'Width', GUICtrlRead($VarWidth), 0)
	_Setting_Write($sPath_ini, 'Images', 'Height', GUICtrlRead($VarHeight), 0)
	Exit
EndFunc